<?php

    class FbuserController extends WebController
    {
        /**
        * @return array action filters
        */
        public function filters()
        {
            return array(
                'accessControl', // perform access control for CRUD operations
                'postOnly + delete', // we only allow deletion via POST request
            );
        }

        /**
        * Specifies the access control rules.
        * This method is used by the 'accessControl' filter.
        * @return array access control rules
        */
        public function accessRules()
        {
            return array(
                array('allow',  // allow all users to perform 'index' and 'view' actions
                    'actions'=>array('login'),
                    'users'=>array('*'),
                ),
                array('allow', // allow authenticated user to perform 'create' and 'update' actions
                    'actions'=>array('logout','update'),
                    'users'=>array('@'),
                ),
                
                array('allow',
                    'actions'=>array('accessFacebookFanPage'),
                    'users'=>array('@'),
                    'expression'    =>  '$user->user->isMod', 
                ),

                array('allow', // allow admin user to perform 'admin' and 'delete' actions
                    'actions'=>array('admin','delete'),
                    'users'=>array('admin'),
                ),
                array('deny',  // deny all users
                    'users'=>array('*'),
                ),
            );
        }



        public function actionLogout()
        {
            Yii::app()->user->logout();
            $this->redirect(Yii::app()->request->urlReferrer);
        }

        public function actionUpdate()
        {    
            $model = Yii::app()->user->user;

            // if it is ajax validation request
            if(isset($_POST['ajax']) && $_POST['ajax']==='update-form')
            {
                echo CActiveForm::validate($model);
                Yii::app()->end();
            }

            if(isset($_POST['User']))
            {
                $post = $_POST['User'];

                $model->attributes = $post;

                if($model->validate())
                {
                    $user = Yii::app()->user->user;
                    $user->setIsNewRecord(FALSE);
                    $user->name = $post['name'];
                    $user->gender = $post['gender'];
                    $user->website = $post['website'];
                    if(isset($post['role'])) $user->role = $post['role'];
                    $user->save();

                    Yii::app()->user->setFlash('success', Yii::t('app', 'You account has been updated successfully.'));

                    $this->refresh();
                }
            }
            $this->pageTitle = "Cập nhật tài khoản";

            $this->render('update', array(
                'model' =>  $model,
            ));
        }



        public function actionLogin()
        {   
            if(!Yii::app()->user->isGuest) $this->redirect($this->baseUrl);
            
            $facebook = new Facebook(array(
                'appId'  => Yii::app()->params->user['fb']['appId'],
                'secret' => Yii::app()->params->user['fb']['secret'],
            ));
            $fb_id = $facebook->getUser();

            if(!$fb_id)
            {
                $loginUrl = $facebook->getLoginUrl(array(
                    'scope' => Yii::app()->params->user['fb']['scope'],
                    'redirect_uri' => $this->createAbsoluteUrl('/web/fbuser/login'),
                ));
                $this->redirect($loginUrl);
            }
            else
            {

                $user = User::model()->findByAttributes(array('fb_id' => $fb_id));

                // if not exist user: create user
                if(!$user){
                    $fbuser = $facebook->api('/me?fields=id,name,birthday,email,gender,link');
                    $user = new User();
                    $user->fb_id = $fbuser['id']; 
                    $user->email = $fbuser['email']; 
                    $user->username = $fbuser['username']; 
                    $user->name = $fbuser['name']; 
                    $user->dob = preg_replace('{(\d{2})/(\d{2})/(\d{4})}', '$3-$1-$2', $fbuser['birthday']); 
                    $user->gender = $fbuser['gender']; 
                    $user->website = $fbuser['link']; 
                    //$user->image = "http://graph.facebook.com/{$fbuser['id']}/picture?type=large"; 
                    $user->created = MyDateTime::getCurrentTime();
                    $user->setIsNewRecord(TRUE);
                    $user->save();
                }

                //auto login
                $userIdentity = new CUserIdentity($user->id, '');
                $userIdentity->setState('id', $user->id);
                $userIdentity->setState('name', $user->name);
                $userIdentity->setState('username', $user->username);                      
                Yii::app()->user->login($userIdentity, 3600*24*365); 
            }

            $this->_openidRedirect();

        }

        private function _openidRedirect(){ 
            $this->render('openid_popup_redirect', array('url' => Yii::app()->request->urlReferrer));
            Yii::app()->end();
        }
        
        
        
        public function actionAccessFacebookFanPage($prevUrl = '/')
        { 
            Yii::import('ext.facebook.src.Facebook');
            $fb = new Facebook(array(
                'appId'  => Yii::app()->params->user['fb']['appId'],
                'secret' => Yii::app()->params->user['fb']['secret'],
            ));

            $fb_id = $fb->getUser();
            $fbLoginUrl = $fb->getLoginUrl(array(
                'scope' => 'publish_stream,manage_pages',
                'redirect_uri' => $this->baseUrl.Yii::app()->request->requestUri,
            ));
            if(!$fb_id){
                Yii::app()->controller->redirect($fbLoginUrl);
            }
            
            // check permissons
            $permissions = $fb->api("/me/permissions");
            if(    ! array_key_exists('publish_stream', $permissions['data'][0])
                || ! array_key_exists('manage_pages', $permissions['data'][0])
            ) {
                Yii::app()->controller->redirect($fbLoginUrl);
            }else{

                Yii::app()->controller->redirect($prevUrl);
            }
        }


    }
